/**
 * 个人资料和历史记录管理
 */
document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const profileForm = document.getElementById('profileForm');
    const profileUsername = document.getElementById('profileUsername');
    const currentPassword = document.getElementById('currentPassword');
    const newPassword = document.getElementById('newPassword');
    const confirmNewPassword = document.getElementById('confirmNewPassword');
    
    // 历史记录相关元素
    const historyTableBody = document.getElementById('historyTableBody');
    const selectAllHistory = document.getElementById('selectAllHistory');
    const deleteSelectedBtn = document.getElementById('deleteSelectedBtn');
    const clearHistoryBtn = document.getElementById('clearHistoryBtn');
    const emptyHistoryMessage = document.getElementById('emptyHistoryMessage');
    
    // 获取当前用户名
    function getCurrentUsername() {
        return localStorage.getItem('username');
    }

    // 获取 token
    function getToken() {
        return localStorage.getItem('token');
    }

    
    // 加载用户个人资料
    async function loadUserProfile() {
        const token = getToken();
        if (!token) return;

        try {
            const response = await fetch('http://localhost:5000/api/auth/profile', {
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                credentials: 'include'
            });

            const data = await response.json();
            if (data.success) {
                profileUsername.value = data.username;
            }
        } catch (error) {
            console.error('获取用户资料失败:', error);
        }
    }

    // 保存个人资料修改
    if (profileForm) {
        profileForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const currentPass = currentPassword.value;
            const newPass = newPassword.value;
            const confirmPass = confirmNewPassword.value;
            const newUsername = profileUsername.value;

            // 验证新密码
            if (newPass && newPass !== confirmPass) {
                alert('新密码与确认密码不一致！');
                return;
            }

            try {
                const token = getToken();
                const response = await fetch('http://localhost:5000/api/auth/update_profile', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({
                        current_password: currentPass,
                        new_password: newPass || undefined,
                        new_username: newUsername
                    })
                });

                const data = await response.json();
                if (data.success) {
                    // 更新本地存储的用户信息
                    if (data.username) {
                        localStorage.setItem('username', data.username);
                    }
                    if (data.token) {
                        localStorage.setItem('token', data.token);
                    }

                    alert('个人资料更新成功！');
                    // 清空密码字段
                    currentPassword.value = '';
                    newPassword.value = '';
                    confirmNewPassword.value = '';
                } else {
                    alert(data.message || '更新失败，请重试');
                }
            } catch (error) {
                console.error('更新个人资料失败:', error);
                alert('更新失败，请检查网络连接');
            }
        });
    }

    // 初始化时加载用户资料
    loadUserProfile();
    
    // 历史记录功能
    const historyKey = 'photoHistory';
    
    // 获取历史记录
    function getHistory() {
        const username = getCurrentUsername();
        if (!username) return [];
        
        const userHistoryKey = `${historyKey}_${username}`;
        const history = localStorage.getItem(userHistoryKey);
        return history ? JSON.parse(history) : [];
    }
    
    // 添加历史记录 (将在photo-upload.js和face-swap.js中调用)
    window.addHistoryRecord = function(type, photoName) {
        const username = getCurrentUsername();
        if (!username) return;
        
        const userHistoryKey = `${historyKey}_${username}`;
        const history = getHistory();
        
        const record = {
            id: Date.now().toString(),
            type,
            photoName,
            timestamp: new Date().toISOString()
        };
        
        history.unshift(record); // 添加到数组开头
        localStorage.setItem(userHistoryKey, JSON.stringify(history));
        
        // 如果当前在历史记录页面，刷新显示
        if (document.getElementById('history').classList.contains('active')) {
            loadHistory();
        }
    };
    
    // 删除历史记录
    function deleteHistoryRecord(id) {
        const username = getCurrentUsername();
        if (!username) return;
        
        const userHistoryKey = `${historyKey}_${username}`;
        let history = getHistory();
        
        history = history.filter(record => record.id !== id);
        localStorage.setItem(userHistoryKey, JSON.stringify(history));
        
        loadHistory();
    }
    
    // 删除多条历史记录
    function deleteSelectedRecords() {
        const username = getCurrentUsername();
        if (!username) return;
        
        const userHistoryKey = `${historyKey}_${username}`;
        let history = getHistory();
        
        // 获取所有选中的记录ID
        const selectedIds = [];
        document.querySelectorAll('.history-record-checkbox:checked').forEach(checkbox => {
            selectedIds.push(checkbox.value);
        });
        
        if (selectedIds.length === 0) {
            alert('请选择要删除的记录');
            return;
        }
        
        if (confirm(`确定要删除选中的${selectedIds.length}条记录吗？`)) {
            history = history.filter(record => !selectedIds.includes(record.id));
            localStorage.setItem(userHistoryKey, JSON.stringify(history));
            
            loadHistory();
        }
    }
    
    // 清空历史记录
    function clearHistory() {
        const username = getCurrentUsername();
        if (!username) return;
        
        if (confirm('确定要清空所有历史记录吗？此操作不可恢复。')) {
            const userHistoryKey = `${historyKey}_${username}`;
            localStorage.setItem(userHistoryKey, JSON.stringify([]));
            loadHistory();
        }
    }
    
    // 加载历史记录到表格
    function loadHistory() {
        if (!historyTableBody) return;
        
        const history = getHistory();
        historyTableBody.innerHTML = '';
        
        if (history.length === 0) {
            if (emptyHistoryMessage) {
                emptyHistoryMessage.classList.remove('hidden');
            }
            if (deleteSelectedBtn) {
                deleteSelectedBtn.classList.add('hidden');
            }
            return;
        }
        
        if (emptyHistoryMessage) {
            emptyHistoryMessage.classList.add('hidden');
        }
        
        history.forEach(record => {
            const row = document.createElement('tr');
            
            // 格式化日期
            const date = new Date(record.timestamp);
            const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            
            row.innerHTML = `
                <td><input type="checkbox" class="history-record-checkbox" value="${record.id}"></td>
                <td>${record.type}</td>
                <td>${record.photoName}</td>
                <td>${formattedDate}</td>
                <td>
                    <button class="history-action-btn delete" data-id="${record.id}">删除</button>
                </td>
            `;
            
            historyTableBody.appendChild(row);
        });
        
        // 绑定删除按钮事件
        document.querySelectorAll('.history-action-btn.delete').forEach(button => {
            button.addEventListener('click', (e) => {
                const id = e.target.dataset.id;
                if (confirm('确定要删除此记录吗？')) {
                    deleteHistoryRecord(id);
                }
            });
        });
        
        // 绑定复选框事件
        document.querySelectorAll('.history-record-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', updateDeleteSelectedButton);
        });
    }
    
    // 根据选择状态更新删除选中按钮
    function updateDeleteSelectedButton() {
        if (!deleteSelectedBtn) return;
        
        const anyChecked = document.querySelectorAll('.history-record-checkbox:checked').length > 0;
        
        if (anyChecked) {
            deleteSelectedBtn.classList.remove('hidden');
        } else {
            deleteSelectedBtn.classList.add('hidden');
        }
    }
    
    // 全选/取消全选
    if (selectAllHistory) {
        selectAllHistory.addEventListener('change', (e) => {
            const isChecked = e.target.checked;
            document.querySelectorAll('.history-record-checkbox').forEach(checkbox => {
                checkbox.checked = isChecked;
            });
            updateDeleteSelectedButton();
        });
    }
    
    // 删除选中记录
    if (deleteSelectedBtn) {
        deleteSelectedBtn.addEventListener('click', deleteSelectedRecords);
    }
    
    // 清空历史记录
    if (clearHistoryBtn) {
        clearHistoryBtn.addEventListener('click', clearHistory);
    }
    
    // 页面加载时初始化
    function initialize() {
        loadUserProfile();
        
        // 如果当前在历史记录页面，加载历史记录
        if (document.getElementById('history') && document.getElementById('history').classList.contains('active')) {
            loadHistory();
        }
    }
    
    initialize();
});